package com.hzhk.happyrent.ui.fragment.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.login.LoginResponse;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.network.MyStringTransResponse;
import com.hzhk.happyrent.ui.activity.personal.ForgetActivity;
import com.hzhk.happyrent.ui.view.ClearEditText;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.PatternStringUtirl;
import com.hzhk.happyrent.utils.StringUtils;
import com.tamic.novate.Throwable;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * <p>
 * to handle interaction events.
 * Use the
 * create an instance of this fragment.
 */
public class LoginFragment extends Fragment {

    @BindView(R.id.act_user_phone)
    ClearEditText actUserPhone;
    @BindView(R.id.act_user_pwd)
    ClearEditText actUserPwd;
    @BindView(R.id.iv_see_pwd)
    ImageView ivSeePwd;
    @BindView(R.id.act_login_layout)
    LinearLayout actLoginLayout;
    @BindView(R.id.act_login_findpassword)
    TextView actLoginFindpassword;
    @BindView(R.id.act_login_submit)
    Button actLoginSubmit;
    Unbinder unbinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        actUserPhone.addTextChangedListener(new TextChange());
        actUserPwd.addTextChangedListener(new TextChange());
        ivSeePwd.setTag(false);
        actLoginSubmit.setEnabled(false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_see_pwd, R.id.act_login_findpassword, R.id.act_login_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_see_pwd:
                changeIt();
                break;
            case R.id.act_login_findpassword:
                startActivity(new Intent(getContext(), ForgetActivity.class));
                break;
            case R.id.act_login_submit:
                String phone = actUserPhone.getText().toString().trim();
                String pwd = actUserPwd.getText().toString().trim();
//                judgePhone(phone, pwd);
                loginIn(phone, pwd);
                break;
        }
    }

    private void loginIn(final String phone, final String pwd) {
        Map<String, Object> params = new HashMap<>();
        params.put("phone", phone);
        params.put("password", pwd);
        HttpManager.getInstance().perform_post(API.LOGIN, params, new MyStringResponse(getContext()) {
            @Override
            public void onNext(Object tag,String response) {
                CodeModel codeModel=new Gson().fromJson(response, CodeModel.class);
                if (codeModel.getErrCode() == 0) {
                    LoginResponse baseModel = new Gson().fromJson(response, LoginResponse.class);

//                    MyPerference.getInstance().setUserInfo(baseModel.getClass(),response);
//                    LoginResponse baseModel1 =MyPerference.getInstance().getUserInfo(LoginResponse.class);
                    MyPerference.getInstance().setUserInfoSave(baseModel.getData().getUser_info().getId(), phone, pwd, baseModel.getData().getUser_info().getIs_auth());
                    ((Activity) getContext()).finish();
                } else {
                    Toast.makeText(getContext(), codeModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

        });
    }

    private void judgePhone(String phone, String pwd) {
        if (TextUtils.isEmpty(phone)) {
            showToast(R.string.tv_phone_is_null);// "请输入手机号"
        } else {
            if (phone.length() < 11) {
                showToast(R.string.tv_phone_isnot_right);// "输入手机号格式不正确"
            } else if (!PatternStringUtirl.isMobileNum(phone)) {
                showToast(R.string.tv_phone_isnot_right);
            } else if (StringUtils.isEmpty(pwd)) {
                showToast(R.string.tv_pwd_is_null);
            } else if (pwd.length() < 6) {
                showToast(R.string.tv_pwd_rule);
//            } else if (!SystemUtils.isLetterDigit(pwd)) {
//                showToast(R.string.tv_pwd_rule_num_and_letter);
            } else {
                loginIn(phone, pwd);
            }
        }
    }

    public void showToast(int id) {
        Toast.makeText(getContext(), id, Toast.LENGTH_SHORT).show();
    }

    private void changeIt() {
        boolean tag = (Boolean) ivSeePwd.getTag();
        if (tag) {
            ivSeePwd
                    .setImageResource(R.drawable.pwd_disvisible);
            ivSeePwd.setTag(false);
            actUserPwd
                    .setTransformationMethod(PasswordTransformationMethod
                            .getInstance());
            actUserPwd.setSelection(actUserPwd
                    .getText().toString().trim().length());
        } else {
            ivSeePwd.setImageResource(R.drawable.pwd_visible);
            ivSeePwd.setTag(true);
            actUserPwd
                    .setTransformationMethod(HideReturnsTransformationMethod
                            .getInstance());
            actUserPwd.setSelection(actUserPwd
                    .getText().toString().trim().length());
        }
    }

    class TextChange implements TextWatcher {

        @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                                  int count) {
            boolean Sign1 = actUserPhone.getText().length() > 10;
            boolean Sign2 = actUserPwd.getText().length() > 5;
            if (Sign1 & Sign2) {
                actLoginSubmit
                        .setBackgroundResource(R.drawable.btn_red_selector);
                actLoginSubmit.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                actLoginSubmit
                        .setBackgroundResource(R.drawable.bg_btn_gray_solid);
                actLoginSubmit.setEnabled(false);
            }

        }
    }
}
